package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"goods-master/cache"
	"goods-master/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))

	Offset := (page - 1) * size

	var shop []models.Shop

	redis_key := "shop_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(Offset).Limit(size).Find(&shop)

		jsonData, _ := json.Marshal(shop)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}

	var total int64
	models.DB.Model(&models.Shop{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  shop,
		"total": total,
	})
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var shop models.Shop

	redis_key := "shop_list_page_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&shop)

		jsonData, _ := json.Marshal(shop)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": shop,
	})
}
